package com.zhdl.hardware.robot.beCurrent.repository.impl;

import cn.hutool.core.util.HexUtil;
import com.google.common.eventbus.Subscribe;
import com.project.command.faq.event.behavior.BehaviorPerform;
import com.zhdl.common.eventbus.center.EventBusCenter;
import com.zhdl.hardware.robot.beCurrent.repository.FairDemoCmdHandleDao;
import com.zhdl.hardware.robot.fair.entity.EventDemoData;
import com.zhdl.hardware.robot.fair.repository.FairCmdHandleDao;
import com.zhdl.modules.tools.CommonCallback;
import com.zhdl.modules.tools.IntToHexUtil;
import com.zhdl.network.asciitcp.EventBusResp;
import com.zhdl.network.strategy.common.ProtocolContext;
import com.zhdl.network.strategy.modbustcp.ModbusASCIIStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class FairDemoCmdHandleDaoImpl implements FairDemoCmdHandleDao {

    /**
     * 法奥机器人-网口
     */
    public String port;
    /**
     * 通信协议处理
     */
    public ProtocolContext protocolContext;
    /**
     * Callback 回调管理
     */
    public Map<String, CommonCallback<String>> commonCallbackMap = new ConcurrentHashMap<>();

    /**
     * 有参构造-添加端口
     *
     * @param port  端口
     * @param behaviorPerform   指令发送·
     */
    public FairDemoCmdHandleDaoImpl(String port, BehaviorPerform behaviorPerform) {
        EventBusCenter.getEventBus().register(this);
        protocolContext = new ProtocolContext(new ModbusASCIIStrategy(port, behaviorPerform));
        this.port = port;
    }

    public String date;

    @Subscribe
    public void dataReception(EventDemoData event) {
        date = event.getDemoData();
        log.info(date);
    }

    /**
     * 法奥机器人-控制机器人动作指令
     *
     * @param cmd 指令
     */
    @Override
    public void FairRobotAction(String cmd, CommonCallback<String> callback){
//        protocolContext.sendCmd(cmd);
//        commonCallbackMap.put(cmd+","+port,callback);
        callback.statusCallback(date);
    }

    /**
     * 法奥机器人-读取机器人当前关节坐标
     *
     * @param cmd 指令
     */
    @Override
    public void FairRobotGetJointPos(String cmd, CommonCallback<String> callback){
        protocolContext.sendCmd(cmd);
        commonCallbackMap.put(cmd,callback);
    }


    /**
     * 通过字节数组转换成 16进制的String类型
     *
     * @param location 世界坐标
     * @return 16进制的世界坐标
     */
    public static String getHexByIntArray(int[] location) {
        StringBuilder stringBuffer = new StringBuilder();
        for (int j : location) {
            String s = IntToHexUtil.intToHex(j);
            stringBuffer.append(s);
        }
        return stringBuffer.toString();
    }
}
